package com.chianghao.rock.system.dao.user;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chianghao.core.mybatis.plugins.Paging;
import com.chianghao.core.mybatis.sql.SqlWrapper;
import com.chianghao.core.mybatis.sql.db_enum.SqlOperators;
import com.chianghao.core.mybatis.sql.db_enum.SqlOrderType;
import com.chianghao.rock.system.entity.User;

@Component
public class UserDao{
	
	@Autowired
	UserMapper mapper;

	public List<User> page(List<Long> allOrganizationIds,boolean isShowNoOrgUser, String name,Paging paging) {
		SqlWrapper sqlWrapper  = new SqlWrapper().order(User::getName, SqlOrderType.asc); 
		boolean hasCondition = false;
		
		if(StringUtils.isNotEmpty(name)||(allOrganizationIds != null&&allOrganizationIds.size()>0)) {
			hasCondition = true;
		}
		
		if(hasCondition) {
			if(isShowNoOrgUser) {
				sqlWrapper.isNull(User::getOrganizationId).orStart();
			}else {
				sqlWrapper.isNotNull(User::getOrganizationId).andStart();
			}
			if(StringUtils.isNotEmpty(name)) {
				sqlWrapper.addCondition(User::getName, SqlOperators.like,name);
				hasCondition = true;
			}
			if(allOrganizationIds != null&&allOrganizationIds.size()>0) {
				sqlWrapper.addInCondition(User::getOrganizationId, allOrganizationIds);
				hasCondition = true;
			}
			sqlWrapper.end();
		}else {
			if(!isShowNoOrgUser) {
				sqlWrapper.isNotNull(User::getOrganizationId);
			}
		}
		
		return this.mapper.queryPageList(paging,sqlWrapper);
	}

	public int queryAccount(String account) {
		SqlWrapper sqlWrapper  = new SqlWrapper().addCondition(User::getAccount, account);
		return this.mapper.count(sqlWrapper);
	}

	
	public int queryAccountNoId(String account, Long id) {
		SqlWrapper sqlWrapper  = new SqlWrapper().addCondition(User::getAccount, account).addCondition(User::getId,SqlOperators.not_equals, id);
		return this.mapper.count(sqlWrapper);
	}

}